package com.boot.unity.api.wx.service;

import com.alibaba.fastjson.JSONObject;
import com.boot.unity.api.constants.NotifyType;
import com.boot.unity.api.utils.ConstantSmsUtils;
import com.boot.unity.api.wx.entity.UserInfo;
import com.boot.unity.api.wx.utils.CharUtil;
import com.boot.unity.api.wx.utils.IpAddress;
import com.boot.unity.api.wx.utils.JacksonUtil;
import com.boot.unity.api.wx.utils.ResponseUtil;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Random;

import static cn.hutool.core.util.ReUtil.isMatch;

@Service
public class WxAuthService {

    @Autowired
    private ConstantSmsUtils constantSmsUtils;

    @Autowired
    private CommonUtilUrlService commonUtilUrlService;


    @Value("${serv.servurl}")
    private String servurl;

    public JSONObject wxLoginAuth(String openId, String sessionKey, UserInfo userInfo , String ipAddr) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("openId", openId);
        jsonObject.put("sessionKey", sessionKey);
        jsonObject.put("userInfo", userInfo);
        jsonObject.put("ipAddr", ipAddr);
        //设置请求头和数据
        RequestBody body = RequestBody.create(mediaType,jsonObject.toString());
        //设置地址，方法，数据格式
        Request request = new Request.Builder()
                .url(servurl+ "/wx/auth/login_by_weixin_new")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                String errno = json.getString("errno");
                if ("0".equals(errno.trim())) {
                    return json;
                } else {
                    String errMsg = json.getString("errmsg");
                    JSONObject resurt = new JSONObject();
                    resurt.put("errno", "403");
                    resurt.put("errmsg", errMsg);
                    return resurt;
                }
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object registerCaptcha(String body) throws Exception {
        String phoneNumber = JacksonUtil.parseString(body, "mobile");
        if (StringUtils.isEmpty(phoneNumber)) {
            return ResponseUtil.badArgument();
        }
        if (!CharUtil.isMobileExact(phoneNumber)) {
            return ResponseUtil.fail(701,"请输入正确的手机号");
        }

        String code = CharUtil.getRandomNum(6);
        System.out.println("-----生成的验证码："+code);
        JSONObject paramJson = new JSONObject();
        paramJson.put("phoneNumber",phoneNumber);
        paramJson.put("code",code);
        String msgUrl = servurl+"/wx/bindManager/checkOrSaveMsg";
        System.out.println("请求参数："+paramJson.toString());
        String result = commonUtilUrlService.post(msgUrl, paramJson.toString());
        System.out.println("请求结果："+result.toString());
        if(!result.trim().equals("1")){
            return ResponseUtil.fail(701, "验证码未超时1分钟，不能发送");
        }else{
            // 发送短信
            constantSmsUtils.send(phoneNumber, NotifyType.CAPTCHA, new String[]{code});
        }
        return ResponseUtil.ok();
    }

    public Object checkLoginByWeixin(String body) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        //设置请求头和数据
        RequestBody body1 = RequestBody.create(mediaType,body);
        //设置地址，方法，数据格式
        Request request = new Request.Builder()
                .url(servurl+ "/wx/auth/checkLoginByWeixin")
                .method("POST", body1)
                .addHeader("Content-Type", "application/json")
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (IOException e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }

    public Object wxInfoById(String uid, String key) {
        OkHttpClient client = new OkHttpClient();
        String url = servurl+ "/wx/auth/wxInfoById?uid=" + uid + "&key=" + key;
        Request request = new Request.Builder()
                .url(url)
                .build();
        String strResult = "";
        try {
            Response response = client.newCall(request).execute();
            strResult = response.body().string();
            if (response.isSuccessful()) {
                // 接口调用成功
                JSONObject json = JSONObject.parseObject(strResult);
                return json;
            } else {
                //接口调用失败
                JSONObject resurt = new JSONObject();
                resurt.put("errno", "403");
                resurt.put("errmsg", "接口访问失败");
                return resurt;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject resurt = new JSONObject();
            resurt.put("errno", "403");
            resurt.put("errmsg", e.getMessage());
            return resurt;
        }
    }
}
